#!/usr/bin/python
# -*- coding:utf-8 -*-
from os.path import join, dirname
from django.utils import timezone
from django.core.management.base import BaseCommand
from mongoengine.errors import DoesNotExist
from utils3 import load_json, hash_hexdigest
from apps.account_manager.models import Permissions, UserGroups, Modules

PERMISSION_COMMON = [
    ["磁盘用量", "/api/v1/system/ddisk/", "GET", "磁盘用量", "磁盘用量"],
    ["获取token过期时间", "/api/v1/gc/token/", "GET", "获取token过期时间", "任何人"],
    ["设置token过期时间", "/api/v1/gc/token/", "PUT", "设置token过期时间", "任何人"],
    ["系统配置", "/api/v1/system/config/", "GET", "查询系统配置", "dns或端口有关配置"],
]

PERMISSION_USER_BASE = [
    ["用户管理", "/api/v1/account/refresh/", "POST", "刷新token", "任何人都能访问"],
    ["用户管理", "/api/v1/account/login/", "POST", "用户登录", "任何人都能访问"],
    ["用户管理", "/api/v1/account/logout/", "GET", "用户退出", "任何人都能访问"],
    ["用户管理", "/api/v1/account/user_info/", "GET", "查询用户信息", "登录用户有效，只能查询自己的信息"],
    ["用户管理", "/api/v1/account/user_info/", "PUT", "账号信息设置", "登录用户有效，只能查询自己的信息"],
    ["用户管理", "/api/v1/account/change_pw/", "POST", "修改密码", "登录用户有效，只能修改自己的密码"],
    ["用户管理", "/api/v1/account/freeze_user/", "POST", "用户注销", "登录用户有效"],
    ["用户管理", "/api/v1/account/mfa_qr/", "GET", "获取mfa二维码", "登录用户有效"],
    ["用户管理", "/api/v1/account/mfa_bind/", "POST", "开启MFA验证", "登录用户有效"],
    ["用户管理", "/api/v1/account/mfa_unbind/", "POST", "关闭MFA验证", "登录用户有效"],
    ["用户管理", "/api/v1/account/mfa_validate/", "POST", "MFA验证", "登录用户有效"],
]

PERMISSIONS_USER = [
    ["权限管理", "/api/v1/account/permission/.*/", "GET", "查询平台所有权限接口", "建议只开放给后台管理员"],
    ["权限管理", "/api/v1/account/permission/", "POST", "增加权限接口", "建议只开放给后台管理员"],
    ["权限管理", "/api/v1/account/permission/.*/", "PUT", "修改权限接口", "建议只开放给后台管理员"],
    ["权限管理", "/api/v1/account/permission/.*/", "DELETE", "删除权限接口", "建议只开放给后台管理员"],
    [
        "权限管理",
        "/api/v1/account/change_user_permission/",
        "POST",
        "管理后台修改用户角色",
        "建议只开放给后台管理员",
    ],
]

PERMISSION_USER_GROUP = [
    ["角色管理", "/api/v1/account/user_group/.*/", "GET", "查询用户组", "建议只开放给后台管理员"],
    ["角色管理", "/api/v1/account/user_group/", "POST", "增加用户组", "建议只开放给后台管理员"],
    ["角色管理", "/api/v1/account/user_group/.*/", "PUT", "修改用户组", "建议只开放给后台管理员"],
    ["角色管理", "/api/v1/account/user_group/.*/", "DELETE", "删除用户组", "建议只开放给后台管理员"],
    [
        "角色管理",
        "/api/v1/account/manage_user_info/.*/",
        "GET",
        "管理后台查询用户信息",
        "建议只开放给后台管理员, 可以查询所有用户的信息",
    ],
    [
        "角色管理",
        "/api/v1/account/manage_user_info/",
        "GET",
        "查询用户信息（临时）",
        "建议只开放给后台管理员, 可以查询所有用户的信息",
    ],
    ["角色管理", "/api/v1/user_group/list", "GET", "查询用户组（临时）", "建议只开放给后台管理员"],
    ["角色管理", "/api/v1/user_group/add", "POST", "增加用户组（临时）", "建议只开放给后台管理员"],
    ["角色管理", "/api/v1/user_group/modify", "PUT", "修改用户组（临时）", "建议只开放给后台管理员"],
    ["角色管理", "/api/v1/user_group/delete", "DELETE", "删除用户组（临时）", "建议只开放给后台管理员"],
    ["模块查询", "/api/v1/user_group/module", "GET", "查询模块", "建议只开放给后台管理员"],
]

PERMISSION_API_MANAGE = [
    ["API管理", "/api/v1/user/input_token/", "GET", "查询所有授权Token", "查询所有授权Token"],
    ["API管理", "/api/v1/user/input_token/.*/", "GET", "查询授权Token", "查询授权Token"],
    ["API管理", "/api/v1/user/input_token/", "POST", "增加授权Token", "增加授权Token"],
    ["API管理", "/api/v1/user/input_token/.*/", "PUT", "修改授权Token", "修改授权Token"],
    ["API管理", "/api/v1/user/input_token/.*/", "DELETE", "删除授权Token", "删除授权Token"],
    ["API管理", "/api/v1/user/output_url/", "GET", "查询所有推送URL", "查询所有推送URL"],
    ["API管理", "/api/v1/user/output_url/.*/", "GET", "查询推送URL", "查询推送URL"],
    ["API管理", "/api/v1/user/output_url/", "POST", "增加推送URL", "增加推送URL"],
    ["API管理", "/api/v1/user/output_url/.*/", "PUT", "修改推送URL", "修改推送URL"],
    ["API管理", "/api/v1/user/output_url/.*/", "DELETE", "删除推送URL", "删除推送URL"],
    ["API管理", "/api/v1/user/output_url_test/", "GET", "推送URL测试", "推送URL测试"],
]

PERMISSION_TARGET = [
    ["业务系统管理", "/api/v1/target/.*/", "GET", "业务系统GET", "建议只开放给后台管理员"],
    ["业务系统管理", "/api/v1/target/.*/", "POST", "业务系统POST", "建议只开放给后台管理员"],
    ["业务系统管理", "/api/v1/target/.*/", "PUT", "业务系统PUT", "建议只开放给后台管理员"],
    ["业务系统管理", "/api/v1/target/.*/", "DELETE", "业务系统DELETE", "建议只开放给后台管理员"],
]

PERMISSION_TARGET_GROUP = [
    ["任务组管理", "/api/v1/target_group/.*/", "GET", "任务组管理GET", "建议只开放给后台管理员"],
    ["任务组管理", "/api/v1/target_group/.*/", "POST", "任务组管理POST", "建议只开放给后台管理员"],
    ["任务组管理", "/api/v1/target_group/.*/", "PUT", "任务组管理PUT", "建议只开放给后台管理员"],
    ["任务组管理", "/api/v1/target_group/.*/", "DELETE", "任务组管理DELETE", "建议只开放给后台管理员"],
]

PERMISSION_TASK = [
    ["任务管理", "/api/v1/task.*/.*/", "GET", "任务GET", "建议只开放给后台管理员"],
    ["任务管理", "/api/v1/task.*/.*/", "POST", "任务POST", "建议只开放给后台管理员"],
    ["任务管理", "/api/v1/task.*/.*/", "PUT", "任务PUT", "建议只开放给后台管理员"],
    ["任务管理", "/api/v1/task.*/.*/", "DELETE", "任务DELETE", "建议只开放给后台管理员"],
    ["任务管理", "/api/v1/session/.*/", "GET", "历史任务GET", "建议只开放给后台管理员"],
    ["任务管理", "/api/v1/session/.*/", "POST", "历史任务任务POST", "建议只开放给后台管理员"],
    ["任务管理", "/api/v1/session/.*/", "PUT", "历史任务任务PUT", "建议只开放给后台管理员"],
    ["任务管理", "/api/v1/session/.*/", "DELETE", "历史任务任务DELETE", "建议只开放给后台管理员"],
    ["任务管理", "/api/v1/event/.*/", "GET", "结果GET", "建议只开放给后台管理员"],
    ["任务管理", "/api/v1/event/.*/", "POST", "结果POST", "建议只开放给后台管理员"],
    ["任务管理", "/api/v1/event/.*/", "PUT", "结果PUT", "建议只开放给后台管理员"],
    ["任务管理", "/api/v1/event/.*/", "DELETE", "结果DELETE", "建议只开放给后台管理员"],
]

PERMISSION_WARN_OVERVIEW = [
    ["告警中心", "/api/v1/warn/list/", "GET", "告警列表", "获取告警列表"],
    ["告警中心", "/api/v1/warn/summary/day/", "GET", "今日告警统计", "今日告警统计"],
    ["告警中心", "/api/v1/warn/summary/week/", "GET", "近一周告警统计", "近一周告警统计"],
]

PERMISSION_WARN_INBOX_MAIL = [
    ["告警中心", "/api/v1/warn/mail/list/", "GET", "站内信列表", "获取站内信列表"],
    ["告警中心", "/api/v1/warn/mail/status/", "PUT", "站内信标记已读", "告警站内信标记已读"],
    ["告警中心", "/api/v1/warn/mail/update-all/", "PUT", "站内信标记全部已读", "告警站内信标记全部已读"],
    ["告警中心", "/api/v1/warn/mail/del-all/", "DELETE", "站内信全部删除", "站内信全部删除"],
    ["告警中心", "/api/v1/warn/mail/del/", "DELETE", "站内信删除", "批量删除站内信"],
]

PERMISSION_WARN = [
    *PERMISSION_WARN_OVERVIEW,
    *PERMISSION_WARN_INBOX_MAIL,
    ["告警中心", "/api/v1/warn/receiver/list/", "GET", "告警联系人列表", "告警联系人列表"],
    ["告警中心", "/api/v1/warn/receiver/[a-z0-9]+/", "GET", "查询告警联系人", "查询告警联系人"],
    ["告警中心", "/api/v1/warn/receiver/del/", "DELETE", "告警联系人删除", "批量删除告警联系人"],
    ["告警中心", "/api/v1/warn/receiver/add/", "POST", "告警联系人添加", "添加告警联系人"],
    ["告警中心", "/api/v1/warn/receiver/[a-z0-9]+/", "PUT", "编辑告警联系人", "编辑告警联系人"],
    ["告警中心", "/api/v1/warn/email/test/", "POST", "发送测试邮件", "发送测试邮件"],
    ["告警中心", "/api/v1/warn/email/", "GET", "获取邮件配置", "获取邮件配置"],
    ["告警中心", "/api/v1/warn/email/", "PUT", "编辑邮件配置", "编辑邮件配置"],
]

PERMISSION_LOG = [
    ["日志中心", "/api/v1/log/config/", "GET", "日志信息", "日志相关的筛选映射"],
    ["操作日志", "/api/v1/log/operation/", "GET", "操作日志列表", "操作日志列表"],
    ["登陆日志", "/api/v1/log/login/", "GET", "登录日志列表", "登录日志列表"],
    ["导出日志", "/api/v1/log/download/", "POST", '导出日志', '导出日志'],
    ['删除日志', '/api/v1/log/delete/', 'POST', '删除日志', '删除日志'],
]

PERMISSION_VUL = [
    ["漏洞信息", "/api/v1/vul/list/", "GET", "漏洞列表", "漏洞列表"],
    ["漏洞信息", "/api/v1/vul/pie/", "GET", "漏洞饼图", "漏洞饼图"],
    ["漏洞信息", "/api/v1/vul/line/", "GET", "漏洞折线图", "漏洞折线图"],
    ["漏洞信息", "/api/v1/vul/enums/", "GET", "漏洞枚举下拉选项", "漏洞枚举下拉选项"],
    ["漏洞信息", "/api/v1/vul/vst/", "GET", "漏洞极值", "漏洞极值"],
]

PERMISSION_KEYWORD = [
    ["敏感词信息", "/api/v1/keyword/count/", "GET", "敏感词数量", "敏感词数量"],
    ["敏感词信息", "/api/v1/keyword/[a-z0-9]+/", "GET", "敏感词类型详情", "敏感词类型详情"],
    ["敏感词信息", "/api/v1/keyword/[a-z0-9]+/", "PUT", "敏感词类型编辑", "敏感词类型编辑"],
    ["敏感词信息", "/api/v1/keyword/whitekey/", "GET", "白名单列表", "白名单列表"],
    ["敏感词信息", "/api/v1/keyword/whitekey/", "POST", "白名单修改", "白名单修改"],
    ["敏感词信息", "/api/v1/keyword/whitekey/", "DELETE", "白名单删除", "白名单删除"],
]

PERMISSION_REPORT = [
    ["报告", "/api/v1/report/exports/list", "GET", "报告下载列表", "报告下载"],
    ["报告", "/api/v1/report/export", "POST", "报告导出", "报告下载"],
    ["报告", "/api/v1/report/exports/download", "GET", "列表报告下载", "报告下载"],
    ["报告", "/api/v1/report/exports/del", "DELETE", "报告删除", "报告下载"],
    ["报告", "/api/v1/report/targets/list", "GET", "待下载报告业务系统列表", "报告下载"],
    ["报告", "/api/v1/report/chapters/list", "GET", "报告章节列表", "报告下载"],
]

STRATEGY = [
    ['策略管理', "/api/v1/strategy/profile/template/search/", "GET", "搜索漏洞模板", "搜索漏洞模板"],
]

PERMISSION_CHANGE_CHECK_CONFIG = [
    ['变更基准设置', "/api/v1/strategy/change_check/", "GET", "查询变更监测基准", "查询变更监测基准"],
    ['变更基准设置', "/api/v1/strategy/change_check/", "PUT", "更新变更监测基准", "更新变更监测基准"],
    ['变更基准设置', "/api/v1/strategy/change_check/", "DELETE", "删除变更监测基准", "删除变更监测基准"],
]

V2_PERMISSION_TARGET = [
    ["业务系统管理", "/api/v2/target/.*/", "GET", "V2业务系统GET", "建议只开放给后台管理员"],
    ["业务系统管理", "/api/v2/target/.*/", "POST", "V2业务系统POST", "建议只开放给后台管理员"],
    ["业务系统管理", "/api/v2/target/.*/", "PUT", "V2业务系统PUT", "建议只开放给后台管理员"],
    ["业务系统管理", "/api/v2/target/.*/", "DELETE", "V2业务系统DELETE", "建议只开放给后台管理员"],
]

PERMISSIONS = [
    ["验证码", "/api/v1/captcha/", "GET", "获取验证码", "任何人都能访问"],
    ["用户管理", "/api/v1/account/register/", "POST", "用户注册", "建议只开放给后台管理员"],
    ["用户管理", "/api/v1/account/manage_register/", "POST", "管理后台创建用户", "建议只开放给后台管理员"],
    [
        "用户管理",
        "/api/v1/account/manage_change_pw/",
        "POST",
        "后台管理员修改密码",
        "建议只开放给后台管理员, 可以强制修改所有用户密码",
    ],
    ["用户管理", "/api/v1/account/change_username/", "POST", "修改用户名", "登录用户有效，只能修改自己的用户名"],
    [
        "用户管理",
        "/api/v1/account/manane_freeze_user/",
        "POST",
        "管理后台冻结用户",
        "建议只开放给后台管理员, 可以强制冻结所有用户",
    ],
    [
        "用户管理",
        "/api/v1/account/manage_active_user/",
        "POST",
        "管理后台激活用户",
        "建议只开放给后台管理员, 可以激活所有用户",
    ],
    *PERMISSION_USER_BASE,
    *PERMISSION_LOG,
    ["日志配置", "/api/v1/log/switch/", "GET", "查询日志配置", "查询日志配置"],
    ["日志配置", "/api/v1/log/switch/", "POST", "修改日志配置", "修改日志配置"],

    ["系统信息", "/api/v1/security/user_info/", "GET", "系统信息", "获取系统信息"],
    ["系统信息", "/api/v1/security/summary/level/", "POST", "系统安全中心态势等级", "安全中心态势等级"],
    [
        "系统信息",
        "/api/v1/security/summary/overview/",
        "POST",
        "安全总览",
        "总请求数、web攻击数、攻击ip数, 默认为当日统计数据，也可改变时间范围",
    ],
    ["系统状态", "/api/v1/system/status/", "GET", "系统状态", "查询系统状态"],
    ["网口配置", "/api/v1/system/network/", "POST", "网口数据信息", "查询网口数据信息"],
    ["系统时间", "/api/v1/system/ntp/", "GET", "系统时间配置信息", "系统时间配置信息"],
    ["系统时间", "/api/v1/system/ntp/", "POST", "系统时间配置信息修改", "系统时间配置信息修改"],
    ["系统升级", "/api/v1/system/update/", "PUT", "修改升级方式", "手动或者自动升级方式"],
    ["系统升级", "/api/v1/system/update/", "GET", "系统版本信息", "查系统版本信息或者数据版本信息"],
    ["系统升级", "/api/v1/system/update/", "POST", "升级系统", "可升级数据或系统"],
    ["系统控制", "/api/v1/system/manage/", "POST", "重启或者关闭设备", "关机或者重启设备"],
    ["产品证书", "/api/v1/system/license/", "GET", "证书信息", "当前设备证书信息"],
    ["产品证书", "/api/v1/system/license/", "POST", "产品证书上传", "上传证书"],
    ["系统配置", "/api/v1/system/config/", "POST", "更改系统配置", "dns或端口配置"],
    ["检测网络", "/api/v1/system/ping/", "POST", "网络检测", "检测对应网口网络状态"],
    [
        "snmp配置",
        "/api/v1/system/snmp/",
        "GET",
        "snmp相关信息",
        "服务是否开启，snmp v1/v2c的团体名， v3的安全用户",
    ],
    [
        "snmp配置",
        "/api/v1/system/snmp/",
        "POST",
        "snmp相关操作",
        "off， on （控制开关服务），set（设置v1/v2团体名）, add(添加v3用户)，delete（删除v3用户）",
    ],
    ["远程协助", "/api/v1/system/support/", "GET", "远程协助开关状态", "查询远程协助开关状态"],
    ["远程协助", "/api/v1/system/support/", "POST", "开关远程协助", "开始或者关闭远程协助"],
    ["路由配置", "/api/v1/system/route/", "GET", "路由列表", "路由列表"],
    ["路由配置", "/api/v1/system/route/", "POST", "路由列表新增", "路由列表新增"],
    ["路由配置", "/api/v1/system/route/", "DELETE", "路由列表删除", "路由列表删除"],
    ["集群节点", "/api/v1/system/node/", "GET", "集群节点", "集群节点"],
    ["集群节点", "/api/v1/system/node/", "POST", "添加集群节点", "集群节点"],
    ["集群节点", "/api/v1/system/node/change/", "POST", "集群节点管理", "集群节点"],
    ["集群信息", "/api/v1/system/load/", "GET", "设备信息", "设备各节点相关系信息"],
    ["集群节点", "/api/v1/system/node-uptime/", "GET", "集群节点开机时长", "集群节点开机时长"],
    ["集群节点", "/api/v1/system/node-upat/", "GET", "集群节点开机时间", "集群节点开机时间"],
    ["状态栏", "/api/v1/system/status_bar/", "GET", "状态栏", "系统状态有关信息"],
    ["备份恢复", "/api/v1/system/backup/", "GET", "备份恢复列表", "备份恢复列表"],
    ["备份恢复", "/api/v1/system/backup/", "DELETE", "备份恢复删除", "备份恢复删除"],
    ["备份恢复", "/api/v1/system/backup-action/", "POST", "备份恢复操作", "备份恢复操作"],
    ["备份恢复", "/api/v1/system/backup-download/", "GET", "备份恢复包下载", "备份恢复列表包下载"],
    ["运行模式", "/api/v1/system/mode/", "POST", "更改运行模式", "有反向代理模式,透明直连模式,旁路模式三种"],
    ["运行模式", "/api/v1/system/mode/", "GET", "查询运行模式", "有反向代理模式,透明直连模式,旁路模式三种"],
    *PERMISSION_WARN,
    *PERMISSIONS_USER,
    *PERMISSION_USER_GROUP,
    *PERMISSION_TARGET,
    *PERMISSION_TARGET_GROUP,
    *PERMISSION_TASK,
    *PERMISSION_VUL,
    *PERMISSION_KEYWORD,
    *PERMISSION_REPORT,
    *PERMISSION_COMMON,
    *STRATEGY,
    *PERMISSION_API_MANAGE,
    *V2_PERMISSION_TARGET,
    *PERMISSION_CHANGE_CHECK_CONFIG,
]


DEFAULT_GROUP_PERMISSIONS = {
    "管理员": [],
    "操作员": [
        *PERMISSION_USER_GROUP,
        *PERMISSION_COMMON,
        *PERMISSION_USER_BASE,
        *PERMISSION_TARGET,
        *PERMISSION_TARGET_GROUP,
        *PERMISSION_TASK,
        *PERMISSION_WARN_OVERVIEW,
        *PERMISSION_WARN_INBOX_MAIL,
        *PERMISSION_VUL,
        *PERMISSION_REPORT,
        *PERMISSION_API_MANAGE,
        *PERMISSION_CHANGE_CHECK_CONFIG,
        ["告警中心", "/api/v1/warn/receiver/list/", "GET", "告警联系人列表", "告警联系人列表"],
        ["告警中心", "/api/v1/warn/receiver/[a-z0-9]+/", "GET", "查询告警联系人", "查询告警联系人"],
        ["告警中心", "/api/v1/warn/receiver/del/", "DELETE", "告警联系人删除", "批量删除告警联系人"],
        ["告警中心", "/api/v1/warn/receiver/add/", "POST", "告警联系人添加", "添加告警联系人"],
        ["告警中心", "/api/v1/warn/receiver/[a-z0-9]+/", "PUT", "编辑告警联系人", "编辑告警联系人"],
        ['策略管理', "/api/v1/strategy/profile/template/search/", "GET", "搜索漏洞模板", "搜索漏洞模板"],
    ],
    "审计员": [
        *PERMISSION_COMMON,
        *PERMISSION_USER_BASE,
        *PERMISSION_LOG,
        ["日志配置", "/api/v1/log/switch/", "GET", "查询日志配置", "查询日志配置"],
        ["日志配置", "/api/v1/log/switch/", "POST", "修改日志配置", "修改日志配置"],
        *PERMISSION_VUL,
    ],
    "api": [*PERMISSION_LOG, *V2_PERMISSION_TARGET]
}


def save_permissions():
    print("初始化权限.......")
    per_names = []
    all_per_name = [per[3] for per in PERMISSIONS]
    if len(all_per_name) > len(set(all_per_name)):
        print('初始化权限失败， 有权限名称重复')
        exit(-1)
    for per in PERMISSIONS:
        try:
            al_per = Permissions.objects.get(path=per[1], method=per[2])
        except DoesNotExist:
            try:
                al_per = Permissions.objects.get(name=per[3])
            except DoesNotExist:
                Permissions(
                    path=per[1],
                    method=per[2],
                    tag=per[0],
                    name=per[3],
                    desc=per[4],
                    created_at=timezone.now(),
                    updated_at=timezone.now(),
                ).save()
            else:
                al_per.delete()
                Permissions(
                    path=per[1],
                    method=per[2],
                    tag=per[0],
                    name=per[3],
                    desc=per[4],
                    created_at=timezone.now(),
                    updated_at=timezone.now(),
                ).save()
        else:
            print(f"已经初始化的权限 {al_per.name}: {al_per.path}=={al_per.method}")
        per_names.append(f"{per[1]}|{per[2]}")
    exist_per = {f"{per.path}|{per.method}" for per in Permissions.objects.all()}
    not_pers = exist_per - set(per_names)
    will_delete_permission = []
    for per in not_pers:
        per_list = per.split("|")
        path, method = per_list[0], per_list[1]
        try:
            permission = Permissions.objects.get(path=path, method=method)
        except DoesNotExist:
            continue
        else:
            permission.delete()
            will_delete_permission.append(permission)
    print("初始化权限完成")
    return will_delete_permission


def save_user_group(del_permission):
    print("初始化用户权限组......")
    del_permission = set(del_permission)
    all_user_group = UserGroups.objects.all()
    all_modules = Modules.objects.all()
    if all_user_group:
        for user_group in all_user_group:
            if user_group.group not in DEFAULT_GROUP_PERMISSIONS:
                _permission = set(user_group.permissions)
                will_save_per = _permission - del_permission
                user_group.permissions = list(will_save_per)
                user_group.save()

    for group, permissions in DEFAULT_GROUP_PERMISSIONS.items():
        permissions = [permission[3] for permission in permissions]
        if not permissions:
            will_save_per = Permissions.objects.all()
        else:
            will_save_per = Permissions.objects.filter(name__in=permissions)
        will_save_per = [p for p in will_save_per]
        try:
            exists_user_group = UserGroups.objects.get(group=group)
        except DoesNotExist:
            UserGroups(
                group=group,
                modules=all_modules,
                permissions=will_save_per,
                created_at=timezone.now(),
                updated_at=timezone.now(),
            ).save()
        else:
            exists_user_group.modules = all_modules
            exists_user_group.permissions = [p for p in will_save_per]
            exists_user_group.updated_at = timezone.now()
            exists_user_group.save()
    print("初始化用户权限组完成......")


def save_modules():
    # 读取modules.json文件中的模块列表
    modules_file = join(dirname(__file__), "modules.json")
    modules = load_json(modules_file)
    module_names = [module['module'] for module in modules]
    print(f"Get module names: {module_names}")

    # 遍历模块列表，如果模块在ModulePermissions表中不存在，则新增
    for module_name in module_names:
        module_hash = hash_hexdigest(module_name)[:32]
        try:
            module_permissions = Modules.objects.get(module_id=module_hash)
        except DoesNotExist:
            module_permissions = None
        if not module_permissions:
            Modules(
                module_id=module_hash,
                module_name=module_name
            ).save()
            print(f"Add module: {module_name}")

    # 获取ModulePermissions表中所有的模块
    all_module_permissions = Modules.objects.all()

    # 遍历ModulePermissions表中的模块，如果模块在modules.json文件中不存在，则删除
    for module_permissions in all_module_permissions:
        if module_permissions.module_name not in module_names:
            module_permissions.delete()
            print(f"Delete module: {module_permissions.module_name}")
    print("Update module permissions success")


class Command(BaseCommand):
    help = "初始化用户权限数据"

    def handle(self, *args, **options):
        save_modules()
        delete_permission = save_permissions()
        save_user_group(delete_permission)
